﻿using AntUnion.FrameWork.Model;
using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Model.ModelsExt;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Web.Service;
using MetaQuotes.MT5WebAPI.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TencentCloud.Ame.V20190916.Models;
using TencentCloud.Bm.V20180423.Models;
using TencentCloud.Tcr.V20190924.Models;
using static AntUnion.FrameWork.Web.Service.AssetsServer;
using static log4net.Appender.RollingFileAppender;

namespace AntUnion.FrameWork.Web.Controllers
{
    /// <summary>
    /// 资产控制器
    /// </summary>
    public class AssetsController : BaseController
    {
        /// <summary>
        /// 获取我的钱包
        /// </summary>
        /// <returns></returns>
        public IActionResult GetCrmWallet()
        {
            ListResult res = new ListResult();
            try
            {
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<CrmWallet> crmWallets = crmService.GetCrmWallet(crmUserModel.Id);
                res.Code = 0;
                res.Data = crmWallets;
                res.Count = crmWallets.Count;
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        ///获取汇率
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetExchangeRate(string from, string to)
        {
            Result res = new Result();
            try
            {
                ExchangeRate exchangeRate = assetsServer.GetExchangeRate(from, to);
                if (exchangeRate != null)
                {
                    res.Code = 0;
                    res.Data = exchangeRate;
                }
                else
                {
                    res.Code = 1;
                    res.Data = LanguageConfig.exchangeRateNull;
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        ///获取汇率
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetRealAmount(string from, string to, decimal amount)
        {
            Result res = new Result();
            try
            {
                RealAmount realAmount = assetsServer.Commission(from, to, amount);
                if (realAmount != null)
                {
                    res.Code = 0;
                    res.Data = realAmount;
                }
                else

                {
                    res.Code = 1;
                    res.Data = LanguageConfig.exchangeRateNull;
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        #region 去设置资金密码


        #endregion

        #region 内部交易

        /// <summary>
        /// 内部交易
        /// </summary>
        /// <returns></returns>
        public IActionResult InternalTransfer()
        {
            ViewBag.hasWallet = false;
            ViewBag.hasMt5User = false;
            ViewBag.hasTradePassword = false;
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            if (crmUser == null)
            {
                return NotFound();
            }
            if (!string.IsNullOrEmpty(crmUser.TradePwd))
            {
                ViewBag.hasTradePassword = true;
            }
            CrmWallet crmWallet = crmService.GetCrmWallet(crmUserModel.Id).FirstOrDefault();
            if (crmWallet != null)
            {
                ViewBag.hasWallet = true;
                ViewBag.crmWalletBalance = crmWallet.Balance.ToString("#,##0.00");
            }
            Mt5User mt5User = mt5Service.GetMt5UserById(crmUserModel.Id);
            if (mt5User != null)
            {
                ViewBag.hasMt5User = true;
                ViewBag.login = mt5User.Login;
                MTAccount mTAccount = new MT5CommonHelper().QueryUserAccount((ulong)mt5User.Login);
                mt5Service.UpdateMt5Balance(mt5User.Login, mTAccount.Balance);
                double balance = assetsServer.GetRealBalance(mTAccount);
                ViewBag.mt5Balance = balance.ToString("#,##0.00");
            }
            return View();
        }

        [HttpPost]
        public JsonResult InternalTransfer(decimal amount, string password, string remarks)
        {
            Result res = new Result();
            try
            {
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
                //确认用户是否存在
                if (crmUser == null)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.crmUserNull;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(password))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.treadPasswordNull;
                    return new JsonResult(res);
                }
                //确认交易账户是否存在
                Mt5User mt5User = mt5Service.GetMt5UserById(crmUserModel.Id);
                if (mt5User == null)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.mt5UserNull;
                    return new JsonResult(res);
                }
                int internaltransferCount = assetsServer.GetInternaltransferCount(crmUserModel.Id);
                if (internaltransferCount >= 3)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.tooMuchInternaltransfer;
                    return new JsonResult(res);
                }
                if (amount <= 0)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.InternaltransferCanNotLessThan0;
                    return new JsonResult(res);
                }
                //确认密码是否正确
                string encryptPwd = SecurityUtil.EncryptPwd(password);
                if (crmUser.TradePwd != encryptPwd)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.tradePwdError;
                    return new JsonResult(res);
                }
                CrmWallet crmWallet = crmService.GetCrmWallet(crmUserModel.Id).FirstOrDefault();
                if (crmWallet == null)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.crmUserNull;
                    return new JsonResult(res);
                }
                if (amount > crmWallet.Balance)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.insufficientCommission;
                    return new JsonResult(res);
                }
                using (mtContext mtContext = new mtContext())
                {
                    CrmWallet myCrmWallet = mtContext.CrmWallets.FirstOrDefault(k => k.CrmId == crmUserModel.Id);
                    string orderId = "";
                    assetsServer.AddCrmInternalTransfer(mtContext, crmUser.Id, mt5User.Login, crmWallet.Id, crmWallet.Balance, amount, remarks, out orderId);
                    assetsServer.AddWalletTransaction(mtContext, crmWallet.Id, WalletTransactionType.cashOut.ToString(), WalletTransactionMode.internalTransferOut.ToString(), myCrmWallet.Balance, amount, orderId);
                    myCrmWallet.Balance = myCrmWallet.Balance - amount;
                    CrmAuditLog crmAuditLog = new CrmAuditLog()
                    {
                        OrderId = orderId,
                        CrmId = crmUserModel.Id,
                        Type = 6,
                        Cont = "提交审核",
                        CreateDate = DateTime.Now
                    };
                    crmService.AddAuditLog(crmAuditLog);
                    int count = mtContext.SaveChanges();
                    res.Code = 0;
                    res.Msg = count == 0 ? LanguageConfig.submitFail : LanguageConfig.submitSuccess;
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }

        #endregion

        #region 支付订单

        /// <summary>
        /// 支付订单
        /// </summary>
        /// <returns></returns>
        public IActionResult PaymentOrder()
        {
            return View();
        }

        #endregion

        #region 钱包流水

        /// <summary>
        /// 获取码表数据 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCode(string type)
        {
            Result res = new Result();
            try
            {
                List<PublicService.CodeModel> codeModels = publicService.GetCode(type);
                res.Code = 0;
                res.Data = codeModels;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        /// 钱包流水
        /// </summary>
        /// <returns></returns>
        public IActionResult WalleStatement()
        {
            return View();
        }

        /// <summary>
        /// 获取全部流水
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="crmId"></param>
        /// <param name="type"></param>
        /// <param name="mode"></param>
        /// <param name="walletId"></param>
        /// <param name="id"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetWalleStatement(int page, int limit, string operationType, string operationMode, string crmWallet, string orderNumber, string changeTime)
        {

            ListResult res = new ListResult();
            try
            {
                int count = 0;
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<WalleStatementModel> walleStatementModels = assetsServer.GetWalleStatement(page, limit, crmUserModel.Id, operationType, operationMode, crmWallet, orderNumber, changeTime, out count);
                res.Code = 0;
                res.Count = count;
                res.Data = walleStatementModels;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        /// 钱包流水
        /// </summary>
        /// <returns></returns>
        public IActionResult WalleStatementDetail(string id)
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            WalleStatementModel walleStatementModel = assetsServer.GetWalleStatementDetail(id, crmUserModel.Id);
            if (walleStatementModel == null)
            {
                return NotFound();
            }
            return View(walleStatementModel);
        }

        #endregion

        #region 交易账号资金流水

        /// <summary>
        /// 交易账号资金流水
        /// </summary>
        /// <returns></returns>
        public IActionResult TradingStatemeng()
        {
            return View();
        }

        /// <summary>
        /// 交易账号流水
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="operationType"></param>
        /// <param name="serialNumber"></param>
        /// <param name="login"></param>
        /// <param name="changeTime"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetTradingStatemeng(int page, int limit, string operationType, string orderNumber, int login, string changeTime)
        {
            ListResult res = new ListResult();
            try
            {
                int count = 0;
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<TradingStatemengModel> tradingStatemengModels = assetsServer.GetTradingStatemeng(page, limit, crmUserModel.Id, operationType, orderNumber, changeTime, out count);
                res.Code = 0;
                res.Count = count;
                res.Data = tradingStatemengModels;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        #endregion

        #region 审核记录

        /// <summary>
        /// 审核记录
        /// </summary>
        /// <returns></returns>
        public IActionResult AuditRecords()
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            meunService.UpdateRead(crmUserModel.Id,2);
            return View();
        }

        /// <summary>
        /// 入金审核
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="login"></param>
        /// <param name="mothod"></param>
        /// <param name="state"></param>
        /// <param name="createTime"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetDeposit(int page, int limit, int? login, int? operationMode, int? state, string createTime, string orderNumber)
        {
            ListResult res = new ListResult();
            try
            {
                int count = 0;
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<DepositModel> crmDeposits = assetsServer.GetDeposit(page, limit, crmUserModel.Id, login, operationMode, state, createTime, orderNumber, out count);
                res.Code = 0;
                res.Count = count;
                res.Data = crmDeposits;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        /// 出金审核
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="login"></param>
        /// <param name="mothod"></param>
        /// <param name="state"></param>
        /// <param name="createTime"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetWithdrawal(int page, int limit, int? login, int? operationMode, int? state, string createTime, string orderNumber)
        {
            ListResult res = new ListResult();
            try
            {
                int count = 0;
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<WithdrawalModel> crmWithdrawals = assetsServer.GetWithdrawal(page, limit, crmUserModel.Id, login, operationMode, state, createTime, orderNumber, out count);
                res.Code = 0;
                res.Count = count;
                res.Data = crmWithdrawals;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        ///内部转账审核
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="login"></param>
        /// <param name="mothod"></param>
        /// <param name="state"></param>
        /// <param name="createTime"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetInternalTransfer(int page, int limit, int? login, int? state, string createTime, string orderNumber)
        {
            ListResult res = new ListResult();
            try
            {
                int count = 0;
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                List<CrmInternaltransferModel> crmInternaltransfers = assetsServer.GetInternalTransfer(page, limit, crmUserModel.Id, state, createTime, orderNumber, out count);
                res.Code = 0;
                res.Count = count;
                res.Data = crmInternaltransfers;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
            }
            return new JsonResult(res);
        }

        #endregion

        /// <summary>
        /// 获取我的钱包金额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetBalance()
        {
            Result res = new Result();
            try
            {
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                //获取钱包信息
                CrmWallet crmWallet = crmService.GetCrmWallet(crmUserModel.Id).FirstOrDefault();
                //获取MT5数据
                Mt5User mt5User = mt5Service.GetMt5UserById(crmUserModel.Id);
                //更新结余
                MTAccount mTAccount = new MT5CommonHelper().QueryUserAccount((ulong)mt5User.Login);
                Hashtable ht = new Hashtable();
                ht.Add("crmId", crmUserModel.Id);
                ht.Add("mt5Id", mt5User.Login);
                ht.Add("crmBalance", crmWallet.Balance.ToString("#,##0.00"));
                ht.Add("mt5Balance", assetsServer.GetRealBalance(mTAccount).ToString("#,##0.00"));
                res.Code = 0;
                res.Data = ht;
                res.Msg = "refreshSuccess";
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                res.Msg = "refreshFailed";
            }
            return new JsonResult(res);
        }


    }
}
